package com.example.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author pulinks
 */
public class FileEncryptionUtil {
    private static final String KEY = "secretkey1234567";
    // 密钥，需要确保安全性

    public static void encryptFile(String filePath) {
        try {
            byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(fileContent);
            Files.write(Paths.get(filePath + ".encrypted"), encryptedBytes);
            System.out.println("文件加密完成：" + filePath + ".encrypted");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String decryptFile(String filePath) {
        try {
            byte[] encryptedContent = Files.readAllBytes(Paths.get(filePath));
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedBytes = cipher.doFinal(encryptedContent);
            Files.write(Paths.get(filePath + ".decrypted"), decryptedBytes);
            System.out.println("文件解密完成：" + filePath + ".decrypted");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }
}